/*
 * $Id$
 */
package py.windmill.dict;

import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author myang
 */
public class MemoryDictionary implements DictionaryService {

    private static final Map<String, List<String>> DICT;

    static {
        load(DICT = new HashMap<String, List<String>>());
    }

    private static void load(final Map<String, List<String>> dict) {
        try {
            final SAXParserFactory parserFactor = SAXParserFactory.newInstance();
            final SAXParser parser = parserFactor.newSAXParser();
            final InputStream is =
              MemoryDictionary.class.getResourceAsStream("/py/windmill/dict/a-z.xml.gz");

            try {
                parser.parse(new GZIPInputStream(is), new DefaultHandler() {
                    private String _word;
                    private List<String> _entries;
                    private String _entry;

                    @Override
                    public void startElement(final String uri,
                                             final String localName,
                                             final String qName,
                                             final Attributes attrs) {
                        if ("w".equals(qName)) {
                            _word = attrs.getValue("text");
                            _entries = new ArrayList<String>();
                        }
                    }

                    @Override
                    public void endElement(final String uri,
                                           final String localName,
                                           final String qName) {
                        if ("e".equals(qName)) {
                            _entries.add(_entry);
                        } else if ("w".equals(qName)) {
                            dict.put(_word, _entries);
                        }
                    }

                    @Override
                    public void characters(final char[] ch,
                                           final int start,
                                           final int length) {
                        _entry = String.copyValueOf(ch, start, length).trim();
                    }
                });
            } 
            finally {
                if (null != is) {is.close();}
            }
        } 
        catch (final Exception ex) {
            System.out.println("===================>" + ex.getMessage());
        }
    }
    private EntryReader _eReader = new EntryDbReader();

    @Override
    public Word selectWord(final String word, final int sn) {
        final List<String> entries = entries(word);
        final int size = entries.size();
        final int index = (sn >= size ? size - 1 : sn);
        final Word w = new Word(word);
        for (int i = 0; i < size; ++i) {
            final String e = entries.get(i);
            if (index == i) {
                w.setSelectedEntryIndex(i).add(e, _eReader.read(e));
            } 
            else {
                w.add(e);
            }
        }
        return w;
    }

    @Override
    public String selectEntry(final String word, final int sn) {
        return _eReader.read(entries(word).get(sn));
    }

    /**
     *
     * @param word
     * @return
     */
    private List<String> entries(final String word) {
        final List<String> entries = DICT.get(word);
        if (null == entries) {
            throw new IllegalArgumentException(word);
        }
        return entries;
    }

    public static void main(final String... args) {
        final DictionaryService ds = DictionaryServiceFactory.memory();
        System.out.println(ds.selectWord("flower", 2));
    }
}
